#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"


void sieve(int fd){
  int prime;
  read(fd, &prime, sizeof(int));
  if (prime == 0){
    close(fd);
    return;
  }
  printf("prime %d\n", prime);
  int fdsNext[2];

  if(pipe(fdsNext) != 0){
    close(fd);
    printf("%d: pipe() failed\n",getpid());
    exit(1);
  }
  int pid = fork();
  if(pid == 0){
    //child
    close(fdsNext[1]);
    sieve(fdsNext[0]);
  }else if(pid > 0){
    //parent
    close(fdsNext[0]);
    int num;
    while(read(fd, &num, sizeof(int)) > 0){
      if(num % prime != 0){
        write(fdsNext[1], &num, sizeof(int));
      }
    }
    
    close(fd);
    close(fdsNext[1]);
    wait(0);
  } else {
    printf("%d: fork() failed\n",getpid());
    exit(1);
  }

}

int
main(int argc, char *argv[])
{
  int fds[2];

  if(pipe(fds) != 0){
    printf("%d: pipe() failed\n",getpid());
    exit(1);
  }

  int pid = fork();
  if(pid == 0){
    //child
    close(fds[1]);
    sieve(fds[0]);
  } else if(pid > 0){
    //parent
    close(fds[0]);

    for (int i = 2; i < 36; i++)
    {
      write(fds[1], &i, sizeof(int));
    }
    close(fds[1]);
    wait(0);
  }else {
    printf("%d: fork() failed\n",getpid());
    
    exit(1);
  }
  

  exit(0);
}
